package com.hp.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.PageInfo;
import com.hp.pojo.Users;
import com.hp.service.IUsersService;

@Controller
@RequestMapping("user")
public class UsersController {
	
	@Resource
	private IUsersService usersService;
	
	/**
	 * 查询所有
	 * @param request
	 * @return
	 */
	@RequestMapping(value="user")
	public String user(HttpServletRequest request) {
		
		
		List<Users> userList = usersService.findUsers();
		
		request.setAttribute("userList", userList);
		
		return "user/user";
	}
	
	/**
	 * 分页查询用户信息
	 */
	@RequestMapping(value="userPage")
	public String userPage(HttpServletRequest request,Integer pageNum,String nameSearch) {
		
		//如果第一次进入页码为空则赋值为1
		if(pageNum==null) {
			pageNum=1;
		}
		
		PageInfo<Users> page=new PageInfo<>();
		page.setPageNum(pageNum);
		
		page.setPageSize(3);
		
		Users users=new Users();
		users.setName1(nameSearch);
		
		PageInfo<Users> pageInfo=usersService.findPageInfo(page,users);
		
		
		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("nameSearch", nameSearch);
		
		return "user/userPage";
	}
	
	/**
	 * 进入添加页面
	 * @return
	 */
	@RequestMapping(value="addUser")
	public String addUser() {
		return "user/addUser";
		
	}
	/**
	 * 保存用户
	 * @param users
	 * @return
	 */
	@RequestMapping(value="addUserInfo")
	public String addUserInfo(Users users,Integer id) {
		
		if(id==null) {
			usersService.insertUsers(users);
		}else {
			System.out.println(id+"id");
			usersService.updateUsersById(users);
		}
		 
		return "redirect:/user/user";
	}
	
/**
 * 删除
 */
	@RequestMapping(value="deleteUser")
	public String deleteUser(Integer id) {
		
		Users users2=usersService.getUserById(id);
		 usersService.deleteUsersById(users2);
		
		return "redirect:/user/user";
	}

	/**
	 * 进入修改页面 
	 */
	@RequestMapping(value = "updateDepart")
	public String updateUsers(Integer id,HttpServletRequest request) {
		Users users=usersService.getUserById(id);
		request.setAttribute("users", users);
		request.setAttribute("id", id);
		return "user/addUser";
	}

}
